/*
 * Alberto Ruiz-Larrea Guillén...11383
 * Erdi Dogruel..................14955
 * Marcos Pérez Martín...........10324
 */

package com.example.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

//This class calculates and updates team ratings
public class UpdateTeamRatings extends AsyncTask<OpenDB, Integer, Long> {

	public UpdateTeamRatings(OpenDB a) {
		abrir = a;
	}

	@SuppressLint("UseValueOf")
	@Override
	protected Long doInBackground(OpenDB... params) {

		SQLiteDatabase watch = params[0].getReadableDatabase();
		String[] col = { OpenDB.id, OpenDB.name, OpenDB.rating };
		Cursor c = watch
				.query(OpenDB.table1, col, null, null, null, null, null);
		c.moveToFirst();
		String[] columns = { OpenDB.id, OpenDB.name, OpenDB.position,
				OpenDB.team, OpenDB.rating };

		SQLiteDatabase read = params[0].getWritableDatabase();
		ContentValues values = new ContentValues();
		while (!c.isAfterLast()) {

			Cursor cursor = watch.query(OpenDB.table2, columns, OpenDB.team
					+ "=?", new String[] { c.getString(1) }, null, null, null);
			cursor.moveToFirst();
			int i = 0;
			int sum = 0;
			while (!cursor.isAfterLast()) {
				sum = sum + cursor.getInt(4);
				cursor.moveToNext();
				i++;
			}
			cursor.close();
			sum = sum / i;
			values.put(OpenDB.rating, sum);
			read.update(OpenDB.table1, values, OpenDB.name + "=?",
					new String[] { c.getString(1) });
			c.moveToNext();
		}
		c.close();

		return null;

	}

	OpenDB abrir;
}
